package com.ycb.bookserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.book.constant.MessageConstant;
import com.book.exception.LoginFailedException;
import com.book.properties.WechatProperties;
import com.book.utils.HttpClientUtil;
import com.ycb.book.dto.UserLoginDTO;

import com.ycb.book.entity.User;
import com.ycb.book.vo.UserReportVO;
import com.ycb.bookserver.mapper.UserMapper;
import com.ycb.bookserver.mapper.WechatMapper;
import com.ycb.bookserver.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN = "http://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WechatMapper wechatMapper;
    @Autowired(required = false)
    private WechatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 员工登录
     *
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        //调用微信接口获得当前用户的openid
        String openid=getOpenid(userLoginDTO.getCode());
        //判断openid是否为空，若为空则表示失败，返回登陆异常
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        User user=wechatMapper.getByOpenid(openid);
        if(user==null){
            user= User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            wechatMapper.insert(user);
        }
        //如果是新用户自动注册

        return user;
    }

    @Override
    public UserReportVO getUser(String idNumber) {
        log.info("到达server层!!!!!");
        return userMapper.getUser(idNumber);
    }

    @Override
    public void add(User user) {
        user.setCreateTime(LocalDateTime.now());
        userMapper.add(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    private String getOpenid(String code){
        //调用微信接口获得当前用户的openid
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", weChatProperties.getCode());
        map.put("grant_type","authorization_code");
        String json= HttpClientUtil.doGet(WX_LOGIN,map);

        JSONObject jsonObject= JSON.parseObject(json);
        String openid=jsonObject.getString("openid");
        return openid;
    }



}
